/*
 * Modified sample code from mgwt showcase
 * Copyright 2010 Daniel Kurka
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package de.dhbw.vs.permachat.client.activities.chatroomlist;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;

import com.google.gwt.core.client.Callback;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.geolocation.client.Geolocation;
import com.google.gwt.geolocation.client.Geolocation.PositionOptions;
import com.google.gwt.geolocation.client.Position;
import com.google.gwt.geolocation.client.Position.Coordinates;
import com.google.gwt.geolocation.client.PositionError;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.event.shared.EventBus;
import com.googlecode.mgwt.dom.client.event.tap.TapEvent;
import com.googlecode.mgwt.dom.client.event.tap.TapHandler;
import com.googlecode.mgwt.mvp.client.MGWTAbstractActivity;
import com.googlecode.mgwt.ui.client.dialog.Dialogs;
import com.googlecode.mgwt.ui.client.widget.celllist.CellSelectedEvent;
import com.googlecode.mgwt.ui.client.widget.celllist.CellSelectedHandler;

import de.dhbw.vs.permachat.client.ActionEvent;
import de.dhbw.vs.permachat.client.ActionNames;
import de.dhbw.vs.permachat.client.ClientFactory;
import de.dhbw.vs.permachat.client.UserInformation;
import de.dhbw.vs.permachat.client.activities.login.LoginPlace;
import de.dhbw.vs.permachat.client.dto.ChatRoom;
import de.dhbw.vs.permachat.client.rest.ChatServiceAsync;

/**
 * @author flo
 * 
 */
public class ChatRoomListActivity extends MGWTAbstractActivity {
	private static final Logger LOGGER = Logger.getLogger(ChatRoomListActivity.class.toString());

	private final ClientFactory clientFactory;
	private List<ChatRoom> chatRoomList;
	private ChatRoomListView view;

	public ChatRoomListActivity(ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
		chatRoomList = new LinkedList<ChatRoom>();

	}

	@Override
	public void start(AcceptsOneWidget panel, final EventBus eventBus) {
		view = clientFactory.getChatRoomListView();

		// view.setLeftButtonText("Home");
		view.setTitle("Chat Rooms");
		view.setChatRoomList(chatRoomList);

		addHandlerRegistration(view.getBackButton().addTapHandler(
				new TapHandler() {

					@Override
					public void onTap(TapEvent event) {
						ActionEvent.fire(eventBus, ActionNames.BACK);

					}
				}));
		
		addHandlerRegistration(view.getRefreshButton().addTapHandler(
				new TapHandler() {

					@Override
					public void onTap(TapEvent event) {
						loadChatRoomList();
					}
				}));
		
		addHandlerRegistration(view.getLogoutButton().addTapHandler(
				new TapHandler() {

					@Override
					public void onTap(TapEvent event) {
						UserInformation.getUser().setName(null);
						clientFactory.getPlaceController().goTo(new LoginPlace());
					}
				}));

		addHandlerRegistration(view.getCellSelectedHandler()
				.addCellSelectedHandler(new CellSelectedHandler() {

					@Override
					public void onCellSelected(CellSelectedEvent event) {
						int index = event.getIndex();

						ChatRoomSelectedEvent.fire(eventBus,
								chatRoomList.get(index));

					}
				}));

		panel.setWidget(view);

		loadChatRoomList();

	}

	private void loadChatRoomList() {
		this.view.showProgressIndicator();
		
		Geolocation geolocation = Geolocation.getIfSupported();
		if(geolocation != null){
			PositionOptions options = new PositionOptions();
			options.setMaximumAge(300000);
			options.setTimeout(10000);
			
			geolocation.getCurrentPosition(new Callback<Position, PositionError>() {
				
				@Override
				public void onSuccess(Position result) {
					Coordinates coordinates = result.getCoordinates();
					GWT.log("Received coordinates: " + coordinates);
					loadChatRoomList(coordinates);
				}
				
				@Override
				public void onFailure(PositionError reason) {
					if(reason.getCode() == PositionError.PERMISSION_DENIED){
						GWT.log("Location permission denied, falling back to alphabetic sorting");
					} else{
						GWT.log("Location exception: " + reason.getMessage());
						//Dialogs.alert("Location Exception", "Exception accessing the current location:\n" + reason.getMessage(), null);
					}
					
					loadChatRoomList(null);
				}
			}, options);
			
		} else{
			loadChatRoomList(null);
		}
	}
	
	private void loadChatRoomList(final Coordinates coordinates){
		MethodCallback<List<ChatRoom>> callback = new MethodCallback<List<ChatRoom>>() {
	
			@Override
			public void onSuccess(Method method, List<ChatRoom> response) {
				LOGGER.info("Received chatroom list");
				chatRoomList = response;
				
				view.setChatRoomList(chatRoomList);
				
				if(coordinates != null){
					view.emphasizeFirstRoom(true);
					view.getFirstHeader().setText("Sorted from near to far");
				} else{
					view.emphasizeFirstRoom(false);
					view.getFirstHeader().setText("Location not available");
				}
				
				
				view.hideProgressIndicator();
			}
	
			@Override
			public void onFailure(Method method, Throwable exception) {
				LOGGER.severe("Exception while getting chatroom list: "
						+ exception.getMessage());
				
				view.hideProgressIndicator();
				Dialogs.alert("Server Call Exception", "Server call failed, message: "
						+ exception.getMessage(), null);
			}
		};
		
		ChatServiceAsync chatService = this.clientFactory.getChatService();
		
		if(coordinates != null){
			chatService.listChatRooms(coordinates.getLatitude(), coordinates.getLongitude(), callback);
		} else{
			chatService.listChatRooms(callback);
		}
		
	}
}
